//
//  RadioCollectionViewController.m
//  A Cup
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 doll. All rights reserved.
//

#import "RadioCollectionViewController.h"
#import "RadioCollectionViewCell.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "Radio.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "User.h"
#import "RadioDetailViewController.h"
#import "MyHeaderView.h"
#import "AboutUsViewController.h"
#import "SaveCupViewController.h"
#import "dataBaseHandle.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface RadioCollectionViewController ()
@property(nonatomic,retain)NSMutableArray *arr;
@property(nonatomic,retain)NSMutableArray *hotArr;
@property(nonatomic,retain)NSMutableArray *allArr;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,copy)NSNumber *total;
@property(nonatomic, assign)BOOL isclick;
@end

@implementation RadioCollectionViewController

static NSString * const reuseIdentifier = @"Cell";
- (void)dealloc
{
    [_arr release];
    [_hotArr release];
    [_allArr release];
    [super dealloc];
}

- (id)init
{
    self.title = @"电台";
    self.arr = [NSMutableArray array];
    self.hotArr = [NSMutableArray array];
    self.allArr = [NSMutableArray array];
    [self.arr addObject:self.hotArr];
    [self.arr addObject:self.allArr];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    return [self initWithCollectionViewLayout:flowLayout];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self hotData];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.frame = CGRectMake(0, 0, WIDTH, self.view.frame.size.height );
    [self.view addSubview:self.collectionView];
    [self.view bringSubviewToFront:self.collectionView];
    [self.collectionView registerClass:[RadioCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    // 页眉注册
    [self.collectionView registerClass:[MyHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    self.page = 0;
    [self method];
    [self.collectionView.legendFooter beginRefreshing];
    // Do any additional setup after loading the view.
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {self.view.frame.size.width,20};
    return size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size = {WIDTH/3 - 25,WIDTH/3};
    return size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    MyHeaderView *headerView;
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            [headerView setLabelText:@"热门电台☂♬♬♬♬♬"];
        }else{
            [headerView setLabelText:@"全部电台☂♬♬♬♬♬"];
        }
    }
    return headerView;
}

- (void)method
{
    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        [self allData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)hotData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"client",@"D8FDE94C-841F-4A4D-B5C4-AAD2472CEE85",@"deviceid",@"",@"auth",@"3.0.1",@"version", nil];
    [manager POST:@"http://api2.pianke.me/ting/radio"parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *radioDic = [responseObject objectForKey:@"data"];
        NSMutableDictionary *hotlist = [radioDic objectForKey:@"hotlist"];
        NSMutableDictionary *alllist = [radioDic objectForKey:@"alllist"];

        for (NSDictionary *hotDic in hotlist) {
            Radio *radio = [[Radio alloc]init];
            [radio setValuesForKeysWithDictionary:hotDic];
            [self.hotArr addObject:radio];
            [radio release];
        }
        for (NSDictionary *allDic in alllist) {
            Radio *radio = [[Radio alloc]init];
            [radio setValuesForKeysWithDictionary:allDic];
            [self.allArr addObject:radio];
            [radio release];
        }
        [self.collectionView reloadData];
        [self.collectionView.legendFooter endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)allData
{
    if ([dataBaseHandle shareDB].state == 1) {
        self.page++;
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *i = [NSString stringWithFormat:@"%ld",self.page*9];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:i,@"start",@"1",@"client",@"D8FDE94C-841F-4A4D-B5C4-AAD2472CEE85",@"deviceid",@"9",@"limit",@"",@"auth",@"3.0.1",@"version", nil];
        [manager POST:@"http://api2.pianke.me/ting/radio_list" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSInteger j = [self.total intValue];
            if (self.page  == (j/9 + 1)) {
                [self.collectionView.footer noticeNoMoreData];
            }else{
                NSMutableDictionary *radioDicDetail = [responseObject objectForKey:@"data"];
                NSMutableArray *list = [radioDicDetail objectForKey:@"list"];
                self.total = [radioDicDetail objectForKey:@"total"];
                for (NSDictionary *d in list) {
                    Radio *radio = [[Radio alloc]init];
                    [radio setValuesForKeysWithDictionary:d];
                    [self.allArr addObject:radio];
                    [radio release];
                }
                [self.collectionView reloadData];
                [self.collectionView.legendFooter endRefreshing];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前无网络，请检查网络后重新尝试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.arr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSMutableArray *tempArr = self.arr[section];
    return tempArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RadioCollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    // Configure the cell
    NSMutableArray *tempArr = self.arr[indexPath.section];
    User *user = [[User alloc]init];
    NSDictionary *userinfo = [tempArr[indexPath.row] userinfo];
    [user setValuesForKeysWithDictionary:userinfo];
    cell.userName.text = [NSString stringWithFormat:@"by:%@",user.uname];
    cell.title.text = [tempArr[indexPath.row]title];
    NSURL *urlIMG = [NSURL URLWithString:[tempArr[indexPath.row]coverimg]];
    [cell.myImageView sd_setImageWithURL:urlIMG];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    RadioDetailViewController *RadioDetail = [[RadioDetailViewController alloc]init];
    NSMutableArray *tempArr = self.arr[indexPath.section];
    Radio *radio = tempArr[indexPath.row];
    RadioDetail.radioid = radio.radioid;
    RadioDetail.title = radio.title;
    NSDictionary *userinfo = [tempArr[indexPath.row] userinfo];
    RadioDetail.userinfo = userinfo;
    [self.navigationController pushViewController:RadioDetail animated:YES];

}
#pragma mark <UICollectionViewDelegate>

/*
 // Uncomment this method to specify if the specified item should be highlighted during tracking
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
 }
 */

/*
 // Uncomment this method to specify if the specified item should be selected
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
 - (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
 }

 - (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
 }

 - (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
 }
 */

@end
